package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author zhangjh
 * @date 2020/10/23
 * @desc 启动类
 * Minicat可以接收到请求进⾏处理，处理之后的结果可以返回浏览器客户端。
 * 1）提供服务，接收请求（Socket通信）
 * 2）请求信息封装成Request对象（Response对象）
 * 3）客户端请求资源，资源分为静态资源（html）和动态资源（Servlet）
 * 4）资源返回给客户端浏览器
 * 我们递进式完成以上需求，提出V1.0、 V2.0、 V3.0版本的需求
 * V1.0需求：浏览器请求http://localhost:8080,返回⼀个固定的字符串到⻚⾯"Hello Minicat!"
 * V2.0需求：封装Request和Response对象，返回html静态资源⽂件
 * V3.0需求：可以请求动态资源（Servlet）
 */
public class Bootstrap {

    private Integer port = 8080;

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    // 定义⼀个线程池
    int corePoolSize = 10;
    int maximumPoolSize =50;
    long keepAliveTime = 100L;
    TimeUnit unit = TimeUnit.SECONDS;
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    RejectedExecutionHandler handler = new
            ThreadPoolExecutor.AbortPolicy();ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            unit,
            workQueue,
            threadFactory,
            handler
    );

    public void start() throws Exception {
        // 加载解析相关的配置， web.xml
        loadServlet();

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=========>start miniCat port: " + port);

        /*
        * 完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回⼀个固定的字符串到⻚
            ⾯"Hello Minicat!"
            * */
        /*while (true) {
            Socket accept = serverSocket.accept();
            OutputStream outputStream = accept.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            accept.close();
        }*/

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源⽂件
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());

            socket.close();
        }*/

        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            // 静态资源处理
            if (servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet请求
                MyServlet httpServlet =
                        (MyServlet)servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }
            socket.close();
        }*/

        /*
            多线程改造（不使⽤线程池）
        */
        /*while(true) {
        Socket socket = serverSocket.accept();
        RequestProcessor requestProcessor = new
        RequestProcessor(socket,servletMap);
        requestProcessor.start();
        }*/
        System.out.println("=========>>>>>>使⽤线程池进⾏多线程改造");
        /*
        多线程改造（使⽤线程池）
        */
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new
                    RequestProcessor(socket, servletMap);
    //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    private Map<String, HttpServlet> servletMap = new
            HashMap<String, HttpServlet>();
        /**
         * 加载解析web.xml，初始化Servlet
         */
        private void loadServlet () {
            InputStream resourceAsStream =
                    this.getClass().getClassLoader().getResourceAsStream("web.xml");
            SAXReader saxReader = new SAXReader();
            try {
                Document document = saxReader.read(resourceAsStream);
                Element rootElement = document.getRootElement();

                List<Node> selectNodes = rootElement.selectNodes("//servlet");
                for (int i = 0; i < selectNodes.size(); i++) {
                    Node node = selectNodes.get(i);
                    Node selectSingleNode = node.selectSingleNode("servlet-name");
                    String servletName = selectSingleNode.getStringValue();
                    Node servletclassElement = node.selectSingleNode("servlet-class");
                    String servletClass = servletclassElement.getStringValue();
                    // 根据servlet-name的值找到url-pattern
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    // /lagou
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                    servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

                /*Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());*/

                }


            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        public static void main (String[]args){
            Bootstrap bootstrap = new Bootstrap();
            try {
                bootstrap.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
